package com.knight.hadoop.day03.bigdata.zk;

import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

public class SimpleZkClient {

	private static final String connectString = "hadoop3:2181,hadoop4:2181,hadoop5:2181";
	private static final int sessionTimeout = 2000;

	private ZooKeeper zooKeeperClient = null;

	@Before
	public void init() throws Exception {
		zooKeeperClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// 收到事件通知后的回调方法
				System.out.println(event.getType() + "---" + event.getPath());

				try {
					zooKeeperClient.getChildren("/", true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Test
	public void testCreate() throws Exception {
		// 参数1：要创建的节点路径 参数2：节点的数据 参数3：节点的权限 参数4：节点的类型 返回参数：保留节点的路径
		String path = zooKeeperClient.create("/eclipse", "hellozk".getBytes(), Ids.OPEN_ACL_UNSAFE,
				CreateMode.PERSISTENT);
		System.out.println("znodePath:" + path);
	}

	/**
	 * 判断znode是否存在
	 */
	@Test
	public void testExist()throws Exception{
		Stat stat = zooKeeperClient.exists("/eclipse", false);
		System.out.println(stat!=null ? "exist" : "not exist");
		System.out.println(stat);
	}
	
	/**
	 * 获取子节点
	 * 
	 * @throws Exception
	 */
	@Test
	public void getChildren() throws Exception {
		List<String> children = zooKeeperClient.getChildren("/", true);
		for (String path : children) {
			System.out.println(path);
		}
		Thread.sleep(Integer.MAX_VALUE);
	}
	
	/**
	 * 获取数据
	 * @throws Exception
	 */
	@Test
	public void getData()throws Exception {
		byte[] data = zooKeeperClient.getData("/eclipse", false, null);
		System.out.println(new String(data));
	}
	
	/**
	 * 删除节点
	 */
	@Test
	public void deleteZnode()throws Exception{
		//-1表示所有版本
		zooKeeperClient.delete("/eclipse", -1);
	}
	
	/**
	 * 修改数据
	 */
	@Test
	public void setData()throws Exception{
		Stat stat = zooKeeperClient.setData("/app1", "appp111".getBytes(), -1);
		System.out.println(stat);
		byte[] data = zooKeeperClient.getData("/app1", false, null);
		System.out.println(new String(data));
	}
}
